package com.hangzhou.xyj.ui.activity;

import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;

import com.hangzhou.xyj.R;
import com.hangzhou.xyj.XYJApplication;
import com.hangzhou.xyj.db.UserDao;
import com.hangzhou.xyj.db.preferences.CommonPreferences;
import com.hangzhou.xyj.event.OperationRespEvent;
import com.hangzhou.xyj.manager.ChatManager;
import com.hangzhou.xyj.manager.IntentManager;
import com.hangzhou.xyj.model.UserModel;
import com.hangzhou.xyj.model.type.EIntentTagType;
import com.hangzhou.xyj.net.handler.LoginHandler;
import com.hangzhou.xyj.net.handler.RegistThirdAccountHandler;
import com.hangzhou.xyj.net.http.HttpLoader;
import com.hangzhou.xyj.net.request.LoginReq;
import com.hangzhou.xyj.net.request.RegistThirdAccountReq;
import com.hangzhou.xyj.ui.activity.base.BaseActivity;
import com.hangzhou.xyj.utils.EventBusUtil;
import com.hangzhou.xyj.utils.LogUtil;
import com.hangzhou.xyj.utils.MD5Util;
import com.hangzhou.xyj.utils.PublicUtil;
import com.hangzhou.xyj.utils.StringUtil;
import com.hangzhou.xyj.utils.ToastUtil;
import com.hangzhou.xyj.utils.constants.DataKey;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;

/**
 * Created by DT-038 on 2015/12/22. 登录页面
 */
public class LoginActivity extends BaseActivity implements OnClickListener {

    private EditText mEtPhone;
    private EditText mEtPassword;
    private String phone;//手机号
    private String TAG = "LoginActivity";
    private boolean isSuccess;
    private ImageButton mIbWeiXin;//微信登录
    private ImageButton mIbQQ;//QQ登录

    @Override
    public void initTop() {
        enableTop(true);
        enableNetErrorView(false);
    }

    @Override
    public void initLayouts() {
        setContentView(R.layout.activity_login);
    }

    @Override
    public void initViews() {
        mEtPhone = findView(R.id.et_phone);
        mEtPassword = findView(R.id.et_password);
        mIbWeiXin = findView(R.id.btn_login_weixin);
        mIbQQ = findView(R.id.btn_login_qq);
    }

    @Override
    public void initDatas() {
        //TODO 读取本地输入过的配置,用户名密码必须加密
        phone = mEtPhone.getText().toString().trim();
        mEtPhone.setSelection(phone.length());

    }

    @Override
    public void initListeners() {
        findViewById(R.id.btn_login).setOnClickListener(this);
        findViewById(R.id.btn_register).setOnClickListener(this);
        findView(R.id.tv_retrieve_password).setOnClickListener(this);
        findView(R.id.btn_login_weixin).setOnClickListener(this);
        findView(R.id.btn_login_qq).setOnClickListener(this);
        findView(R.id.btn_login_weibo).setOnClickListener(this);
        findView(R.id.mtv_user_agreement).setOnClickListener(this);
    }

    /**
     * 校验输入
     */
    private boolean checkInput() {
        String phone = mEtPhone.getText().toString().trim();
        String password = mEtPassword.getText().toString().trim();
        //校验手机号是否为空
        if (StringUtil.isBlank(phone)) {
            ToastUtil.show("手机号为空，请输入手机号");
            return false;
        }
        //校验手机号是否合法
        if (!PublicUtil.isMobilePhone(phone)) {
            ToastUtil.show("手机号输入非法，请重新输入");
            mEtPhone.setText("");
            return false;
        }
        //密码是否为空
        if (StringUtil.isBlank(password)) {
            ToastUtil.show("密码为空，请输入密码");
            return false;
        }
        return true;
    }

    /**
     * SSO授权:有客户端用客户端授权，没有的话启动网页登录授权
     *
     * @param platName 平台名称
     */
    private void authPlat(final String platName) {
//        ShareManager.getInstance().init(XYJApplication.mAppContext);
//        ShareSDK.initSDK(this);
        Platform platform = ShareSDK.getPlatform(platName);
        platform.SSOSetting(false);  //设置false表示使用SSO授权方式
        //判断是否已经授权，如果授权就删除授权资料，否则就执行授权：
        if (platform.isValid()) {
            platform.removeAccount();
        }
        LogUtil.d(TAG, "platName==" + platName);
        showLoadingDialog();
        platform.setPlatformActionListener(new PlatformActionListener() {

            @Override
            public void onComplete(Platform platform, int action, HashMap<String, Object> hashMap) {
                LogUtil.d(TAG, "授权成功");
                Iterator iter = hashMap.entrySet().iterator();
                while (iter.hasNext()) {
                    Map.Entry entry = (Map.Entry) iter.next();
                    Object key = entry.getKey();
                    Object val = entry.getValue();
                    LogUtil.d(TAG, "key===" + key + "   value==" + val);
                }


                //用户资源都保存到res
                //通过打印res数据看看有哪些数据是你想要的
                if (action == Platform.ACTION_USER_INFOR) {
                    PlatformDb platDB = platform.getDb();//获取数平台数据DB
                    //通过DB获取各种数据
                    platDB.getToken(); //这个暂时不用
                    final String accountName = platDB.getUserId();
                    final String nickname = platDB.getUserName();
                    final String sex = platDB.getUserGender();
                    final String headPic = platDB.getUserIcon();

                    LogUtil.d(TAG, "accountName==" + accountName
                                    + "nickname==" + nickname
                                    + "sex==" + sex
                                    + "headPic==" + headPic
                    );

                    String type = "";

                    if (platName.equals(QQ.NAME)) {
                        type = RegistThirdAccountReq.TYPE_QQ;
                    } else if (platName.equals(Wechat.NAME)) {
                        type = RegistThirdAccountReq.TYPE_WEIXIN;
                    }
                    //注册
                    final String finalType = type;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            registerThirdAccount(accountName, nickname, headPic, sex.equals("m") ? "男" : "女", finalType);
                        }
                    });
                }
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                LogUtil.d(TAG, "授权错误" + throwable.getMessage());
                setAuthButtonEnable(true);
            }

            @Override
            public void onCancel(Platform platform, int i) {
                setAuthButtonEnable(true);
                LogUtil.d(TAG, "取消授权");
            }
        });
        platform.showUser(null);//获取自己的资料
    }

    @Override
    protected void onStop() {
        super.onStop();
        hideLoadingDialog();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_login:
                if (checkInput()) {
                    //校验通过则登录
                    phone = mEtPhone.getText().toString().trim();
                    final String password = mEtPassword.getText().toString().trim();
                    login(phone, password);
                }
                break;
            case R.id.btn_register:
                IntentManager.getInstance().goRegisterActivity(this);
                break;
            case R.id.tv_retrieve_password://找回密码
                IntentManager.getInstance().goRetrievePasswordActivity(this);
                break;
            case R.id.btn_login_weixin: //微信授权
                authPlat(Wechat.NAME);
                setAuthButtonEnable(false);
                break;
            case R.id.btn_login_qq: //qq授权
                authPlat(QQ.NAME);
                setAuthButtonEnable(false);
                break;
            case R.id.btn_login_weibo: //微博授权
//                authPlat(SinaWeibo.NAME);
                break;
            case R.id.mtv_user_agreement://用户协议
                Intent intent = new Intent(mContext, WebActivity.class);
                intent.putExtra(DataKey.INDEX, "http://app.zheliyouxi.com/xiyouji/agreement.html");
                intent.putExtra(DataKey.TITLE, "用户协议");
                intent.putExtra(DataKey.INTENT_TAG, EIntentTagType.TAG_USER_AGREEMENT.getValue());
                IntentManager.getInstance().goActivity(mContext, intent);
                break;
            default:
                break;
        }
    }

    /**
     * 设置授权登录按钮是否可用
     *
     * @param enable
     */
    private void setAuthButtonEnable(boolean enable) {
        mIbWeiXin.setEnabled(enable);//防止重复点击
        mIbWeiXin.setEnabled(enable);//防止重复点击
    }

    /**
     * 登陆操作
     *
     * @param phone
     * @param pwd
     */
    private void login(String phone, String pwd) {
        LoginReq req = new LoginReq(phone, MD5Util.md5(pwd));
        HttpLoader.getInstance().sendRequest(new LoginHandler(req, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                LogUtil.d(TAG, "登录成功...");
                loginSuccess(model);
            }
        }, 0));
    }

    private void loginSuccess(Object model) {
        //登录成功，保存用户信息到数据库
        UserDao dao = new UserDao(mContext);
        dao.addUser((UserModel) model);
        //保存userId到配置中，用于标识读取数据库信息
        String userId = ((UserModel) model).getUserId() + "";
        CommonPreferences.saveUserId(mContext, userId);
        //保存一份到应用中
        XYJApplication.getInstance().setUserInfo((UserModel) model);

        //登录环信
        ChatManager.getInstance().login(userId, "123456");
        isSuccess = true;
        //关闭界面
        closeActivity();
    }

    /**
     * @param accountName 用户名
     * @param nickname    昵称
     * @param headPic     头像
     * @param sex         性别
     * @param type        账号类型：微信；新浪微博；QQ
     * @return
     * @author yaohuix
     * @date 2016/5/11 11:25
     */
    public void registerThirdAccount(String accountName, String nickname, String headPic, String sex, String type) {
        LogUtil.d(TAG, "开始注册");
        RegistThirdAccountReq registThirdAccountReq = new RegistThirdAccountReq(accountName, nickname, headPic, sex, type);
        HttpLoader.getInstance().sendRequest(new RegistThirdAccountHandler(registThirdAccountReq, new MyHttpResponseListener() {
            @Override
            public void onSuccess(Object model) {
                super.onSuccess(model);
                LogUtil.d(TAG, "注册成功");
                //注册之后登陆
                loginSuccess(model);
            }
        }, 0));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //发送事件
        OperationRespEvent event = new OperationRespEvent();
        if (isSuccess) {
            event.setIsSuccess(true);
        } else {
            event.setIsSuccess(false);
        }
        event.setTag(TAG);
        EventBusUtil.postEvent(event);
    }
}
